<template>
  <div>
    <!--   面包屑导航区域-->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
<!--    卡片视图-->
    <el-card>
<!--      添加角色按钮区域-->
      <el-row>
        <el-col>
          <el-button type="primary" @click="showAddRoleDialog">添加角色</el-button>
        </el-col>
      </el-row>
<!--角色列表区域-->
      <el-table :data="roleList"  border stripe>
<!--        展开列-->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row :class="['bdbottom','vcenter',index1===0?'bdtop':'']"
                    v-for="(item1,index1) in scope.row.children"
                    :key="item1.id">
<!--              渲染一级权限-->
              <el-col :span="5">
                <el-tag closable @close="removeRightById(scope.row,item1.id)">{{item1.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
<!--              渲染二级和三级权限-->
              <el-col :span="19">
<!--                通过for循环嵌套渲染二级权限-->
                <el-row :class="['vcenter',index2===0?'':'bdtop']" v-for="(item2,index2) in item1.children"
                        :key="item2.id">
                  <el-col :span="6">
                    <el-tag type="success" closable
                            @close="removeRightById(scope.row,item2.id)">{{item2.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag type="warning" v-for="(item3) in item2.children"
                            :key="item3.id" closable @close="removeRightById(scope.row,item3.id)">{{item3.authName}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
<!--        索引列-->
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作" prop="level" width="300px">
          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row.id)">编辑</el-button>
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeRoleById(scope.row.id)">删除</el-button>
            <el-button type="warning" icon="el-icon-setting" size="mini" @click="showSetRightDialog(scope.row)">分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <el-dialog
      title="分配权限"
      :visible.sync="setRightDialogVisible"
      width="50%" @close="setRightDialogClose">
<!--      树形控件 rightList中的id来作为每个树节点唯一标识的属性，-->
      <el-tree :data="rightList" :props="treeProps"
               show-checkbox node-key="id" default-expand-all
               :default-checked-keys="defKeys" ref="treeRef"></el-tree>
      <span slot="footer" class="dialog-footer">
    <el-button @click="setRightDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="allowRights">确 定</el-button>
  </span>
    </el-dialog>
    <el-dialog
      title="添加角色"
      :visible.sync="showAddRoleDialogVisible"
      width="50%"
    >
      <!--      内容主体区域-->
      <el-form :model="addRolesForm" :rules="addRolesFormRules" ref="addRolesFormRefs" label-width="80px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addRolesForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
        <el-input v-model="addRolesForm.roleDesc" ></el-input>
      </el-form-item>
      </el-form>
      <!--      底部区域-->
      <span slot="footer" class="dialog-footer">
    <el-button @click="resetInfo">取 消</el-button>
    <el-button type="primary" @click="addRoles" >确 定</el-button>
  </span>
    </el-dialog>
    <el-dialog
      title="修改角色"
      :visible.sync="editDialogVisible"
      width="50%">
      <el-form :model="editRolesForm" :rules="addRolesFormRules" ref="editRolesFormRef" label-width="80px" >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editRolesForm.roleName" ></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editRolesForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
    <el-button @click="resetEditInfo">取 消</el-button>
    <el-button type="primary" @click="editRole">确 定</el-button>
  </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "Roles",
  data(){
    return{
      editDialogVisible:false,
      editRolesForm:{

      },
      addRolesFormRules:{
        roleName:[
          {required:true,message:'请输入角色名称',trigger:'blur'}
        ],
        roleDesc:[
          {required:true,message:'请输入角色描述',trigger:'blur'}
        ]
      },
      addRolesForm:{
        roleName:'',
        roleDesc:''
      },
      showAddRoleDialogVisible:false,
    //  所有角色列表数据
      roleList:[],
      setRightDialogVisible:false,
      rightList:[],
      //属性控件的属性绑定对象
      treeProps:{
        //label是要嵌套显示的值，children是实现父子之间关系的值

        label:'authName',
        children:'children'
      },
      //默认选中的节点id值数组
      defKeys:[],
      //当前即将分配权限的角色id
      roleId:''
    }
  },
  created() {
    this.getRoleList()
  },
  methods:{
    removeRoleById(id){
      //  弹框提示用户是否删除数据
      this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(()=>{
        this.$http.delete('roles/'+id).then(({data:res})=>{
          if (res.meta.status!==200) return this.$message.error(res.meta.msg)
          this.getRoleList()
          return this.$message.success(res.meta.msg)
        })
      }).catch(()=>{
        return this.$message.info('已取消删除')
      })
    },
    resetEditInfo(){
      this.editDialogVisible=false
      this.$refs.editRolesFormRef.resetFields()
    },
    showEditDialog(id){
      this.$http.get('roles/'+id).then(({data:res})=>{
        if (res.meta.status!==200) return this.$message.error('查询角色信息失败！')
        this.editRolesForm=res.data

      })
      this.editDialogVisible=true
    },
    editRole(){
      this.$refs.editRolesFormRef.validate(valid=>{
        if (!valid) return this.$message.error('修改失败，信息格式有误，请重新填写')
        //可以发起修改用户的网络请求
        this.$http.put('roles/'+this.editRolesForm.roleId,
          {roleName:this.editRolesForm.roleName,roleDesc:this.editRolesForm.roleDesc})
          .then(({data:res})=>{
            if (res.meta.status!==200) return  this.$message.error('更新失败,请稍后再试')
            this.editDialogVisible = false
            this.getRoleList()
            this.$message.success(res.meta.msg)
          })
      })
    },
    addRoles(){
      this.$refs.addRolesFormRefs.validate(valid=>{
        if (!valid) return this.$message.error('添加失败，信息格式有误，请重新填写')
        //可以发起添加角色的网络请求
        this.$http.post('roles',this.addRolesForm).then(({data:res})=>{
          if (res.meta.status!==201) return  this.$message.error('添加角色失败,请稍后再试')
          this.$message.success('角色添加成功')
          this.showAddRoleDialogVisible = false
          this.getRoleList()
        })
      })
    },
    resetInfo(){
      this.showAddRoleDialogVisible=false
      this.$refs.addRolesFormRefs.resetFields()
    },
    showAddRoleDialog(){
      this.showAddRoleDialogVisible=true
    },
    //点击为角色分配权限
    allowRights(){
      const keys=[
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      const idStr= keys.join(',')
      this.$http.post(`roles/${this.roleId}/rights`,{rids:idStr}).then(({data:res})=>{
        if (res.meta.status!==200) return this.$message.error('分配权限失败！')
        this.$message.success('分配权限成功！')
        this.getRoleList()
        this.setRightDialogVisible=false
      })
    },
    //监听对话框的关闭事件
    setRightDialogClose(){
      this.defKeys=[]
    },
    //  通过递归的形式获取角色下所有三级权限的id，并保存到defKeys数组中
    getLeafKeys(node,arr){
      //如果当前node节点不包含children属性，则是第三节点，将id加入到node中
      if (!node.children){
        return arr.push(node.id)
      }
      node.children.forEach(item=>{
        this.getLeafKeys(item,arr)
      })
    },
    //展示分配权限的对话框
    showSetRightDialog(role){
      this.roleId=role.id
      //获取所有权限数据
      this.$http.get('rights/tree').then(({data:res})=>{
        if (res.meta.status!==200) return this.$message.error('获取权限数据失败')
        //把获取到的权限数据保存到data中
        this.rightList=res.data
      })
      //  递归获取三级节点的id
      this.getLeafKeys(role,this.defKeys)
      this.setRightDialogVisible=true
    },
    getRoleList(){
      this.$http.get('roles').then(({data:res})=>{
        if (res.meta.status!==200) return this.$message.error('获取角色列表失败')
        this.roleList=res.data
      })
    },
    //根据id删除对应的权限
    removeRightById(role,rightId){
      this.$confirm('此操作将删除该权限, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(()=>{
        this.$http.delete(`roles/${role.id}/rights/${rightId}`).then(({data:res})=>{
          if (res.meta.status!==200) return this.$message.error('删除权限失败！')
          // this.getRoleList() 会刷新整个列表
          //重新赋值一下权限
          role.children=res.data
        })
      }).catch(()=>{
        this.$message.info('已取消删除！')
      })
    }
  }
}
</script>

<style scoped>
.el-tag{
  margin: 7px;
}
.bdtop{
  border-top: 1px solid #eee;
}
.bdbottom{
  border-bottom: 1px solid #eee;
}
.vcenter{
  display: flex;
  align-items: center;
}
</style>
